import pymysql
from .LogUtil import loggUitl
from config import Config as conf

logger = loggUitl()
class MysqlUtil :
 # 游标多会影响，故初始化不获取
    def __init__(self,
                 host =conf.meta_data_host,
                 user = conf.meta_data_user,
                 passwd = conf.meta_data_passwd,
                 db=conf.meta_data_db,
                 charset=conf.meta_data_charset
                ):
        self.conn = pymysql.connect(
            host=host,
            user=user,
            passwd=passwd,
            db=db,
            charset=charset
        )
        if self.conn:
            logger.info(f'数据库[{self.conn.db.decode()}]已连接')
        pass

    def close(self):
        if self.conn :
            self.conn.close()
            logger.info(f'数据库[{self.conn.db.decode()}]已关闭')
            self.conn = None
        pass
    def query(self, sql):
        cursor = self.conn.cursor()
        try:
            cursor.execute(sql)
            result = cursor.fetchall()
            logger.info(f'方法query-查询语句:{sql}')
            logger.info(f'查询结果:{result}')
        except Exception as e :
            logger.error(f'方法query执行错误:{e}')
        cursor.close()
        return result

    def select_db(self, db_name):
        self.conn.select_db(db_name)
        pass
    def execute_sql(self, sql):
        cursor = self.conn.cursor()
        flag = False
        try :
            cursor.execute(sql)
            self.conn.commit()
            logger.info(f'执行语句:{sql}')
            flag = True
        except Exception as e:
            logger.error(f'方法execute_sql执行错误:{e}')
            flag = False
        cursor.close()
        return flag

    def check_table_exits_and_create (self, db_name,table_name,table_clumn):
        self.conn.select_db(db_name)

        tables  = self.query('show tables')
        result =  (table_name,) in tables
        if not result:
            create_table_Sql = f'create table {table_name}({table_clumn})'
            if self.execute_sql(create_table_Sql):
                logger.info(f'创建表{db_name}.{table_name}')
        else:
            logger.info(f'表已存在[{db_name}.{table_name}]')
        pass


# 获取处理过的文件名
def get_process_file(db_util,
                     db_name = conf.meta_data_db,
                    table_name = conf.meta_table,
                     create_clos = conf.meta_cloumn
                     ) -> None:
    db_util.check_table_exits_and_create(db_name=db_name,
                                         table_name=table_name,
                                         table_clumn=create_clos)
    results = db_util.query(f'select file_name from {table_name}')
    file_list = []
    for row in results:
        file_list.append(row[0])
    return file_list

if __name__ == '__main__':
    get_process_file(MysqlUtil())